package com.zxmzy.scaffold.core.utils

import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.os.LocaleList
import java.util.Locale

/**
 * @author zhangxiaoming
 * @date 2023/8/31
 * @description
 */
object LanguageUtil {
    const val ZH_CN: String = "zh_CN"
    private const val key: String = "language"
    fun getSystemLanguage(): String {
        return Locale.getDefault().language + "-" + Locale.getDefault().country
    }

    fun getCurrentLanguage(): Locale {
        val locale: Locale? = MMKVUtil.decodeObj(key, Locale::class.java)
        return locale ?: Locale.getDefault()
    }

    fun switchChinese() {
        changeLanguage(Locale.SIMPLIFIED_CHINESE)
    }

    fun switchEnglish() {
        changeLanguage(Locale.US)
    }

    fun switchLanguage(locale: Locale) {
        changeLanguage(locale)
    }

    private fun changeLanguage(locale: Locale) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            setConfiguration(appContext, locale)
        }
    }

    fun setConfiguration(context: Context, locale: Locale) {
        //获取应用程序的所有资源对象
        val res = context.resources
        //获取设置对象
        val configuration = res.configuration
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N_MR1) {
            configuration.setLocale(locale)
        } else {
            configuration.setLocale(locale)
            configuration.setLocales(LocaleList(locale))
        }
        context.createConfigurationContext(configuration)
//        val dm = res.displayMetrics
//        res.updateConfiguration(configuration, dm)
    }

    fun attachBaseContext(context: Context): Context {
        val locale = getCurrentLanguage()
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            updateResources(context, locale)
        } else {
            context
        }
    }

    @TargetApi(Build.VERSION_CODES.N)
    private fun updateResources(context: Context, locale: Locale): Context {
        val res = context.resources
        val configuration = res.configuration
        configuration.setLocale(locale)
        configuration.setLocales(LocaleList(locale))
        return context.createConfigurationContext(configuration)
    }
}